/**
 * @author Created by qiush on 2017-06-05.
 */

import * as React from 'react';
import {ipcRenderer, nativeImage, remote} from 'electron';
import AbsSimpleAttrRenderer from './AbsSimpleAttrRenderer';

class ImageAttrRenderer extends AbsSimpleAttrRenderer<undefined> {

  protected renderContent() {
    const {attribute} = this.props;
    const attrVal: any = this.getAttrVal();

    return (
      <div className="Attribute-item-content-group">
        <input name={attribute.name} value={attrVal} onChange={this.changeHandler} placeholder={attribute.placeholder}
               style={{width: '60%'}}/>
        <button type="button" className="Attribute-color-picker-btn input-add-on" onClick={this.showImagePicker}
                style={{width: '40%'}}>上传图片
        </button>
      </div>
    );
  }

  private saveImage(imagePath) {
    // 读取图片
    const image: Electron.NativeImage = nativeImage.createFromPath(imagePath);
    if (image.isEmpty()) {
      return;
    }

    const {designId, target} = this.props;
    /*store.dispatch({
     type: ActionType.ADD_RESOURCE,
     designId,
     resourceName: imagePath,
     resourceContent: image.toDataURL()
     });*/

    /*console.info('before', remote.getGlobal('sharedObjects').resources);
     remote.getGlobal('sharedObjects').resources[imagePath] = image.toDataURL();
     console.info('after', remote.getGlobal('sharedObjects').resources);
     setTimeout(() => {
     console.info('timeout', remote.getGlobal('sharedObjects').resources);
     }, 100);*/

    ipcRenderer.send('resource', imagePath);

    if (target === 'attrVals') {
      this.notifyViewChanged(`buf://${imagePath}`);
    } else if (target === 'style') {
      this.notifyViewChanged(`url("buf://${imagePath}")`);
    }
  }

  private showImagePicker = () => {
    remote.dialog.showOpenDialog({
      title: '选择图片',
      filters: [
        {
          name: '图片',
          extensions: ['png', 'jpg', 'jpeg']
        }
      ]
    }, fileNames => {
      if (fileNames && fileNames.length === 1) {
        this.saveImage(fileNames[0]);
      }
    });
  }
}

export default ImageAttrRenderer;
